﻿using Newtonsoft.Json;
using RXY_Mall.Api.Common;
using RXY_Mall.Api.Models;
using RXY_Mall.Core;
using RXY_Mall.Data;
using RXY_Mall.Domain;
using RXY_Mall.Services;
using RXY_Mall.Services.User;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace RXY_Mall.Api.Controllers
{
    /// <summary>
    /// 购物车接口
    /// </summary>
    [RoutePrefix("Cart")]
    [ApiSecurityFilter]
    public partial class CartController : BaseApiController
    {
        private RXY_MallContext db;
        private UserService userService;

        public CartController()
        {
            db = new RXY_MallContext();
            userService = new UserService();
        }

        //获得购物车列表
        //修改购物车
        //删除购物车

        #region 购物车
        /// <summary>
        /// 添加购物车
        /// </summary>
        /// <param name="input">地址信息输入信息</param>
        /// <returns>data:地址ID</returns>
        [HttpPost]
        [Route("AddCart")]
        public async Task<Response<CartOutput>> AddCart(AddCartInput input)
        {
            Response<CartOutput> result = new Response<CartOutput>();
            result.code = 0;
            result.msg = "";
            try
            {
                if (input.quantity < 1)
                {
                    input.quantity = 1;
                }

                var sku = await db.gw_goods_skus
                    .Include(g => g.gw_goods)
                    .Include(g => g.gw_goods.gw_goods_property)
                    .Select(g => new
                    {
                        g.id,
                        g.deleted,
                        goods_deleted = g.gw_goods.deleted,
                        g.is_sale,
                        g.conversion_rate,
                        goods_is_sale = g.gw_goods.gw_goods_property.is_sale,
                        g.limit_quantity,
                        g.gw_goods.category_id,
                        g.goods_id,
                        g.gw_goods.type_id,
                        g.gw_goods.shop_id,
                        g.gw_goods.company_id,
                    })
                    .FirstOrDefaultAsync(g => g.id == input.sku_id);

                if (sku == null || sku.deleted || sku.goods_deleted)
                {
                    result.msg = "商品不存在";
                    return result;
                }
                if (!sku.is_sale || !sku.goods_is_sale)
                {
                    result.msg = "该商品暂无法销售";
                    return result;
                }

                if (input.quantity > sku.limit_quantity)
                {
                    result.msg = "商品最多可购买" + sku.limit_quantity;
                    return result;
                }

                //购物车内是否存在该商品
                var cart = await db.gw_carts.FirstOrDefaultAsync(c => c.user_id == input.user_id && c.sku_id == input.sku_id);
                if (cart == null)
                {
                    cart = new gw_cart()
                    {
                        add_time = DateTime.Now,
                        user_id = input.user_id,
                        category_id = (int)sku.category_id,
                        goods_id = sku.goods_id,
                        goods_type = sku.type_id,
                        shop_id = sku.shop_id,
                        quantity = input.quantity,
                        sku_id = input.sku_id,
                        company_id = sku.company_id,
                        conversion_rate = sku.conversion_rate,
                    };

                    db.gw_carts.Add(cart);
                }
                else
                {
                    if (cart.quantity + input.quantity > sku.limit_quantity)
                    {
                        result.msg = "商品最多可购买" + sku.limit_quantity;
                        return result;
                    }

                    cart.quantity += input.quantity;
                    db.Entry(cart).Property(c => c.quantity).IsModified = true;
                }

                int row = await db.SaveChangesAsync();
                if (row > 0)
                {
                    result.code = 1;
                    result.msg = "加入成功";

                    result = await GetCart(cart.id);
                }
                else
                {
                    result.code = 0;
                    result.msg = "加入失败";
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 修改购物车
        /// </summary>
        /// <param name="input">地址信息输入信息</param>
        /// <returns>data:地址ID</returns>
        [HttpPost]
        [Route("UpdateCart")]
        public async Task<Response<bool>> UpdateCart(UpdateCartInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            try
            {
                gw_cart cart = await db.gw_carts.FindAsync(input.cart_id);
                if (cart == null)
                {
                    result.msg = "已删除";
                    return result;
                }

                if (cart.user_id != input.user_id)
                {
                    result.msg = "非法访问";
                    return result;
                }

                if (input.quantity < 0)
                {
                    input.quantity = 1;
                }

                //删除
                if (input.quantity == 0)
                {
                    return await DeleteCarts(new DeleteCartInput() { cart_ids = new List<int>() { input.cart_id }, user_id = input.user_id });
                }

                var sku = await db.gw_goods_skus
                    .Include(g => g.gw_goods)
                    .Include(g => g.gw_goods.gw_goods_property)
                    .Select(g => new
                    {
                        g.id,
                        g.deleted,
                        goods_deleted = g.gw_goods.deleted,
                        g.is_sale,
                        goods_is_sale = g.gw_goods.gw_goods_property.is_sale,
                        g.limit_quantity
                    })
                    .FirstOrDefaultAsync(g => g.id == cart.sku_id);

                if (sku == null || sku.deleted || sku.goods_deleted)
                {
                    result.msg = "商品不存在";
                    return result;
                }
                if (!sku.is_sale || !sku.goods_is_sale)
                {
                    result.msg = "该商品暂无法销售";
                    return result;
                }

                if (input.quantity > sku.limit_quantity)
                {
                    result.msg = "商品最多可购买" + sku.limit_quantity;
                    return result;
                }

                cart.quantity = input.quantity;
                db.Entry(cart).Property(c => c.quantity).IsModified = true;
                int row = await db.SaveChangesAsync();
                if (row > 0)
                {
                    result.code = 1;
                    result.msg = "修改成功";
                    result.data = true;
                    //result = await GetCart(cart.id);
                }
                else
                {
                    result.code = 0;
                    result.msg = "修改失败";
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 删除购物车
        /// </summary>
        /// <param name="input">地址信息输入信息</param>
        [HttpPost]
        [Route("DeleteCarts")]
        public async Task<Response<bool>> DeleteCarts(DeleteCartInput input)
        {
            Response<bool> result = new Response<bool>();
            result.code = 0;
            result.msg = "";
            result.data = false;
            try
            {
                var carts = await db.gw_carts.Where(c => input.cart_ids.Contains(c.id) && c.user_id == input.user_id).ToListAsync();
                if (carts == null || carts.Count == 0)
                {
                    result.msg = "无数据";
                    return result;
                }

                List<gw_cart_history> cart_history = new List<gw_cart_history>();
                foreach (var item in carts)
                {
                    cart_history.Add(new gw_cart_history()
                    {
                        add_time = DateTime.Now,
                        category_id = item.category_id,
                        company_id = item.company_id,
                        goods_id = item.goods_id,
                        goods_type = item.goods_type,
                        quantity = item.quantity,
                        shop_id = item.shop_id,
                        sku_id = item.sku_id,
                        user_id = item.user_id,

                    });
                }
                db.gw_cart_histories.AddRange(cart_history);

                db.gw_carts.RemoveRange(carts);
                int row = await db.SaveChangesAsync();
                if (row > 0)
                {
                    result.code = 1;
                    result.msg = "删除成功";
                    result.data = true;
                }
                else
                {
                    result.code = 1;
                    result.msg = "删除失败";
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得购物车商品
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetCartList")]
        public async Task<Response<List<CartOutput>>> GetCartList(int user_id)
        {
            Response<List<CartOutput>> result = new Response<List<CartOutput>>();
            result.code = 0;
            result.msg = "";
            try
            {
                var output = await db.gw_carts
                                .Include(g => g.gw_goods_sku)
                                .Include(g => g.gw_goods)
                                .Where(g => g.user_id == user_id)
                                .Select(g => new CartOutput()
                                {
                                    cart_id = g.id,
                                    category_id = (int)g.gw_goods.category_id,
                                    goods_id = g.goods_id,
                                    goods_name = g.gw_goods.name,
                                    goods_type = (GoodsType)g.goods_type,
                                    shop_id = g.gw_goods.shop_id,
                                    sku = new SkuOutput()
                                    {
                                        sku_id = g.sku_id,
                                        is_sale = g.gw_goods_sku.is_sale,
                                        limit_quantity = g.gw_goods_sku.limit_quantity,
                                        market_price = g.gw_goods_sku.market_price,
                                        sale_price = g.gw_goods_sku.sale_price,
                                        json_specs = g.gw_goods_sku.specs,
                                        thumb_url = g.gw_goods_sku.thumb_url,
                                        quantity = g.quantity,
                                        cart_id = g.id,
                                    },
                                })
                                .OrderBy(c => c.shop_id).ThenBy(c => c.category_id).ThenBy(c => c.goods_id)
                                .ToListAsync();

                if (output != null)
                {
                    foreach (var item in output)
                    {
                        item.sku.specs = JsonConvert.DeserializeObject<List<SpecOutput>>(item.sku.json_specs);
                        item.sku.thumb_url = HostHelper.GetImgUrl(item.sku.thumb_url);
                    }
                }

                result.code = 1;
                result.msg = "获取成功";
                result.data = output;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得购物车
        /// </summary>
        /// <param name="cart_id">购物车Id</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetCart")]
        public async Task<Response<CartOutput>> GetCart(int cart_id)
        {
            try
            {
                Response<CartOutput> result = new Response<CartOutput>();
                result.code = 0;
                result.msg = "";

                var output = await db.gw_carts
                                .Include(g => g.gw_goods_sku)
                                .Include(g => g.gw_goods)
                                .Where(g => g.id == cart_id)
                                .Select(g => new CartOutput()
                                {
                                    cart_id = g.id,
                                    category_id = (int)g.gw_goods.category_id,
                                    goods_id = g.goods_id,
                                    goods_name = g.gw_goods.name,
                                    goods_type = (GoodsType)g.goods_type,
                                    shop_id = g.gw_goods.shop_id,
                                    sku = new SkuOutput()
                                    {
                                        sku_id = g.sku_id,
                                        is_sale = g.gw_goods_sku.is_sale,
                                        limit_quantity = g.gw_goods_sku.limit_quantity,
                                        market_price = g.gw_goods_sku.market_price,
                                        sale_price = g.gw_goods_sku.sale_price,
                                        json_specs = g.gw_goods_sku.specs,
                                        thumb_url = g.gw_goods_sku.thumb_url,
                                        quantity = g.quantity,
                                        cart_id = cart_id,
                                    },
                                })
                                .FirstOrDefaultAsync();

                if (output != null)
                {
                    output.sku.specs = JsonConvert.DeserializeObject<List<SpecOutput>>(output.sku.json_specs);
                    output.sku.thumb_url = HostHelper.GetImgUrl(output.sku.thumb_url);
                    result.code = 1;
                    result.data = output;
                    return result;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
            return null;
        }


        /// <summary>
        /// 获得购物车历史
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <param name="page_index"></param>
        /// <param name="page_size"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetCartHistoryList")]
        public Response<IPagedList<CartOutput>> GetCartHistoryList(int user_id = 0, int page_index = 1, int page_size = 20)
        {
            Response<IPagedList<CartOutput>> result = new Response<IPagedList<CartOutput>>();
            result.code = 0;
            result.msg = "";
            try
            {
                var sources = db.gw_cart_histories
                                .Include(g => g.gw_goods_sku)
                                .Include(g => g.gw_goods)
                                .Where(g => g.user_id == user_id)
                                .Select(g => new CartOutput()
                                {
                                    add_time = g.add_time,
                                    cart_id = g.id,
                                    category_id = (int)g.gw_goods.category_id,
                                    goods_id = g.goods_id,
                                    goods_name = g.gw_goods.name,
                                    goods_type = (GoodsType)g.goods_type,
                                    shop_id = g.gw_goods.shop_id,
                                    sku = new SkuOutput()
                                    {
                                        sku_id = g.sku_id,
                                        is_sale = g.gw_goods_sku.is_sale,
                                        limit_quantity = g.gw_goods_sku.limit_quantity,
                                        market_price = g.gw_goods_sku.market_price,
                                        sale_price = g.gw_goods_sku.sale_price,
                                        json_specs = g.gw_goods_sku.specs,
                                        thumb_url = g.gw_goods_sku.thumb_url,
                                        quantity = g.quantity,
                                        cart_id = g.id,
                                    },
                                })
                                .OrderByDescending(g => g.add_time);

                IPagedList<CartOutput> output = new PagedList<CartOutput>(sources, page_index, page_size);
                if (output != null)
                {
                    foreach (var item in output)
                    {
                        item.sku.specs = JsonConvert.DeserializeObject<List<SpecOutput>>(item.sku.json_specs);
                        item.sku.thumb_url = HostHelper.GetImgUrl(item.sku.thumb_url);
                    }
                }

                result.code = 1;
                result.msg = "获取成功";
                result.data = output;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = 2;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        #endregion

    }
}
